<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\cdc;

use app\command\BaseWork;
use app\command\DailyStatWork;
use app\model\CrontabTaskModel;
use app\service\cdc\cost\flow\FlowInterface;
use app\service\cdc\cost\TaskAccountService;
use app\service\client\AccountService;
use app\service\CrontabTaskService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * @deprecated
 */
class CostBePullCostTaskWork extends BaseWork implements DailyStatWork
{
    public ?string $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('cost_be_pull_cost_task_work');
        // 设置参数
        $this->setDescription('生成拉取任务')
            ->addArgument('task_type', Argument::REQUIRED, '任务类型  1：账户 2：视频  3：图片')
            ->addArgument('date_type', Argument::REQUIRED, '日期类型 1:昨日  2:今日')
            ->addArgument('media_id', Argument::OPTIONAL, '媒体id')
            ->addArgument('date', Argument::OPTIONAL, '日期 Ymd')
            ->setHelp('php think cost_be_pull_cost_task_work [task_type] [date_type] [media_id] [date]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $mediaId = intval($input->getArgument('media_id'));
        $taskType = intval($input->getArgument('task_type'));
        $dateType = $input->getArgument('date_type');
        if ($dateType == 1) {
            $dateInt = date('Ymd', strtotime('-1 day'));
        } elseif ($dateType == 2) {
            $dateInt = date('Ymd');
        } else {
            $dateInt = $input->getArgument('date') ?: date('Ymd', strtotime('-1 day'));
        }
        $dateInt = intval($dateInt);
        $this->setTag($mediaId . '-' . $taskType);
        $this->getOutputMessage('生成拉取任务开始！');
        // 获取所有有效账户
        try {
            $accountIds = AccountService::getSortPuttingAccount($dateInt, $mediaId);

            if (! $accountIds) {
                $this->getOutputMessage('暂无账户！');
                return false;
            }

            $service = TaskAccountService::getCostFlowService($taskType);
            if (! $service instanceof FlowInterface) {
                $this->getOutputMessage('服务类型未知！');
                return false;
            }

            foreach ($accountIds as $accountId) {
                $accountModel = AccountService::getAccountModel($accountId);
                if (! $accountModel) {
                    $this->getOutputMessage('账户模型不存在！account_id:' . $accountId);
                    continue;
                }

                $res = $service->setTaskAccountData($accountModel, $dateInt);

                if (! $res) {
                    $this->getOutputMessage('account_id:' . $accountModel->getAttr('account_id') . '错误：' . $service::getError(0));
                }
            }
            if ($dateType == 1) {
                // 昨日更新任务执行时间
                CrontabTaskService::setSingleTask($this);
            }
        } catch (\Exception $e) {
            $this->getOutputMessage('错误：' . $e->getMessage());
            echo $e->getLine() . PHP_EOL;
            echo $e->getFile() . PHP_EOL;
            echo $e->getTraceAsString() . PHP_EOL;
        }
        $this->getOutputMessage('生成拉取任务结束！');
    }
}
